package com.hzy.fivepalace.db.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzy.fivepalace.db.dao.DtsGroupOpenDetailMapper;
import com.hzy.fivepalace.db.domain.DtsGroupOpenDetail;
import com.hzy.fivepalace.db.domain.DtsGroupOpenList;
import com.hzy.fivepalace.db.domain.DtsOrder;
import com.hzy.fivepalace.db.domain.DtsUser;
import com.hzy.fivepalace.db.service.DtsGroupOpenDetailService;
import com.hzy.fivepalace.db.service.base.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 参团详情Service业务层处理
 *
 * @author ruoyi
 * @date 2022-11-07
 */
@Service
public class DtsGroupOpenDetailServiceImpl extends BaseServiceImpl<DtsGroupOpenDetailMapper, DtsGroupOpenDetail> implements DtsGroupOpenDetailService {

    @Resource
    private DtsGroupOpenDetailMapper groupOpenDetailMapper;

    @Override
    public DtsGroupOpenDetail getMyDetailByGroup(int userId, int groupId, int openId) {

        QueryWrapper<DtsGroupOpenDetail> qw = new QueryWrapper<>();
        qw.eq("group_id", groupId);
        qw.eq("group_open_id", openId);
        qw.eq("user_id", userId);
        qw.last("limit 1");
        DtsGroupOpenDetail groupOpenDetail = groupOpenDetailMapper.selectOne(qw);
        return groupOpenDetail;
    }

    @Override
    @Transactional
    public int addGroupOpenDetail(DtsUser user, DtsGroupOpenList groupOpenList, DtsOrder order) {
        int ret = 0;
        try{
            QueryWrapper<DtsGroupOpenDetail> qw = new QueryWrapper<>();
            qw.eq("group_id",groupOpenList.getGroupId());
            qw.eq("group_open_id",groupOpenList.getId());
            qw.eq("user_id",user.getId());
            qw.last("limit 1");
            DtsGroupOpenDetail groupOpenDetail = groupOpenDetailMapper.selectOne(qw);
            if(groupOpenDetail == null){
                groupOpenDetail = new DtsGroupOpenDetail();
                groupOpenDetail.setGroupId(groupOpenList.getGroupId());
                groupOpenDetail.setGroupOpenId(groupOpenList.getId());
                groupOpenDetail.setUserId(user.getId());
                groupOpenDetail.setCreateTime(new Date());
//                0 - 参与成功  1 - 拼团 成功
                groupOpenDetail.setState(0);
                groupOpenDetail.setOrderId(order.getId());
                groupOpenDetail.setRefundStatus(0);
                ret = groupOpenDetailMapper.insert(groupOpenDetail);
            }else{
                ret = 1;
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }
}
